<!--
 * @Date: 2024-07-30 16:20:46
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2025-02-26 09:40:00
 * @Description: 
-->
<template>
  <div class="sql-config-panel">
    <div class="panel-header">
      <!-- <el-button size="default" type="default" @click="analysisClick">接口解析</el-button>
      <el-button size="default" type="primary" @clßick="saveClick">保存</el-button> -->
    </div>
    <div class="panel-center">
      <div class="panel-center-from">
        <el-form
          ref="reqFormRef"
          :="reqFormAttrs"
          :model="reqFormData"
        >
          <el-form-item label="接口地址" prop="url">
            <el-input placeholder="请输入" v-model="reqFormData.url"></el-input>
          </el-form-item>
          <el-form-item label="请求方式" prop="method">
            <el-select
              style="width: 100%"
              v-model="reqFormData.method"
              placeholder="请选择"
              popper-class='designer-select-fixed'
            >
              <el-option
                v-for="item in RequestTypes.getData()"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="请求风格">
            <el-radio-group v-model="reqFormData.restful">
              <el-radio-button :value="false">常规</el-radio-button>
              <el-radio-button :value="true">Restful</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="参数类型" prop="paramsType">
            <el-radio-group v-model="reqFormData.paramsType">
              <el-radio-button
                v-for="item in RequestParamTypes.getData()"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="请求参数" style="margin-bottom: 0">
            <el-switch
              v-model="reqFormStore.paramsIsFunc"
              size="default"
              inline-prompt
              style="--el-switch-on-color: #409eff; --el-switch-off-color: #13ce66"
              active-text="方法"
              inactive-text="对象"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="panel-center-other">
        <div class="func-item" v-show="reqFormStore.paramsIsFunc">
          <span class="item-text">function () {</span>
        </div>
        <AceCodeEditor mode="javascript" theme="sqlserver" v-model="reqFormStore.paramsContent" :border="true" />
        <div class="func-item" v-show="reqFormStore.paramsIsFunc">
          <span class="item-text">}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { XEUtils } from '@/utils'

import { AceCodeEditor } from '@/components/vf-editor'

import { reactive, ref, inject, onMounted, onBeforeMount, nextTick, computed } from 'vue';

import { useTableApi } from '@/api/api-table';

import { RequestTypes, RequestParamTypes } from '@/base/pojo/RequestType.js'

// 获取父级传递数据
const axiosConfig = inject('axiosConfig');
const getTableConfigData = inject('getTableConfigData')
const optionModel = getTableConfigData().optionModel

// 请求的API
const { analyseReq } = useTableApi(axiosConfig.request);

const emits = defineEmits(['save', 'analysis', 'formatter']);

// 配置信息
const analyseInfo = reactive({
  fieldList: optionModel.dataConfig.fieldList,
});

// 表单Ref对象
const reqFormRef = ref(null)
// 表单数据
const reqFormData = reactive({
  url: '',
  method: 'POST',
  params: '',
  restful: false,
  paramsType: 'data',
})
// 表单属性
const reqFormAttrs = reactive({
  labelWidth: '100px',
  rules: {
    url: [{ required: true, message: '该项为必填项', trigger: ['blur', 'change'] }],
    method: [{ required: true, message: '该项为必填项', trigger: ['blur', 'change'] }],
    paramsType: [{ required: true, message: '该项为必填项', trigger: ['blur', 'change'] }],
  }
})
// 表单数据集
const reqFormStore = reactive({
  paramsIsFunc: false,
  paramsContent: ''
})

const initReqFormData = () => {
  const { dataConfig } = optionModel;
  Reflect.ownKeys(reqFormData).forEach(key => {
    if (dataConfig.reqConfig.hasOwnProperty(key)) reqFormData[key] = XEUtils.clone(dataConfig.reqConfig[key], true);
  });
  setReqParams(reqFormData.params);
}

// 设置编辑框参数信息
const setReqParams = content => {
  if (content && XEUtils.isObject(content)) {
    reqFormStore.paramsIsFunc = false;
    reqFormStore.paramsContent = JSON.stringify(content, null, '  ');
  }
  if (content && XEUtils.isString(content)) {
    reqFormStore.paramsIsFunc = true;
    reqFormStore.paramsContent = content.replace(`func:`, '');
  }
};
// 转换编辑框参数信息
const parseReqParams = () => {
  let result = reqFormStore.paramsContent;
  if (reqFormStore.paramsIsFunc) {
    result = `func:${result}`;
  } else {
    try {
      result = result ? JSON.parse(result) : '';
    } catch (err) {
      // validate = false;
      console.error('参数解析出错，请确认参数信息！');
    }
  }
  return result;
};

/**
 * 保存按钮点击
 */
const saveClick = () => {
  reqFormRef.value.validate((valid, fields) => {
    if (valid) {
      const resultForm = XEUtils.clone(reqFormData, true);
      resultForm.params = parseReqParams(reqFormData.params);
      const result = {
        reqConfig: resultForm,
        ...analyseInfo,
      };
      emits('save', { ...XEUtils.clone(result, true) });
    } else {
      console.warn('校验未通过！');
    }
  });
}

/**
 * 解析按钮点击
 */
const analysisClick = () => {
  reqFormRef.value.validate((valid, fields) => {
    if (valid) {
      const reqOptions = {
        url: reqFormData.url,
        method: reqFormData.method,
      };
      // 转换参数
      reqOptions[reqFormData.paramsType] = parseReqParams(reqFormData.params);
      console.log(reqOptions)
      // analyseReq(reqOptions)
      //   .then(res => {
      //     const { data } = res;
      //     analyseInfo.fieldList = data;
      //     const result = {
      //       columns: XEUtils.clone(data, true),
      //       fieldList: XEUtils.clone(data, true),
      //     };
      //     emits('analysis', result);
      //   })
      //   .catch(err => {
      //     console.error(err);
      //   });
    } else {
      console.warn('校验未通过！');
    }
  });
}

onBeforeMount(() => {
  initReqFormData()
})
defineExpose({
  saveClick
})

</script>

<style lang="scss" scoped>
.sql-config-panel {
  height: 100%;
  padding: 0 8px;
  display: flex;
  flex-direction: column;
  .panel-header {
    height: 30px;
    margin: 0.6em 0;
    text-align: right;
    position: relative;
  }
  .panel-center {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin-bottom: 6px;
    &-other {
      display: flex;
      flex-direction: column;
      flex: 1;
    }
    .func-item {
      width: 100%;
      background-color: var(--el-color-info-light-9);
      color: var(--el-color-info);
      .item-text {
        padding: 0 8px;
        font-weight: 600;
      }
    }
  }
}
:deep(.el-form-item) {
  margin-bottom: 16px;
}
</style>